from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.urls import reverse

from myadmin.models import Shop, User, Category, Product


def index(request):
    """ 项目前台大堂点餐首页 """
    return redirect(reverse("web_index"))


def webindex(request):
    """ 项目前台大堂点餐首页 """
    cartlist = request.session.get('cartlist', {})
    total_money = 0  # 总金额
    # 累加总金额
    for obj in cartlist.values():
        total_money += obj['num'] * obj['price']
    request.session['total_money'] = total_money

    context = {'categorylist': request.session.get("categorylist", {}).items()}
    return render(request, "web/index.html", context)


def login(request):
    """ 加载登陆表单页 """
    shoplist = Shop.objects.filter(status=1)
    context = {'shoplist': shoplist}
    return render(request, "web/login.html", context)


def dologin(request):
    """ 执行登陆操作 """
    try:
        # 选择店铺判断
        if request.POST['shop_id'] == '0':
            return redirect(reverse('web_login') + "?errinfo=1")

        # 验证码校验
        if request.POST['code'] != request.session['verifycode']:
            return redirect(reverse('web_login') + "?errinfo=2")

        # 获取登录者信息
        user = User.objects.get(username=request.POST['username'])
        # 判断当前用户是否正常或管理员
        if user.status == 6 or user.status == 1:
            # 判断登录密码是否相同
            import hashlib
            md5 = hashlib.md5()
            s = request.POST['pass'] + user.password_salt  # 从表单中获取密码并添加干扰值
            md5.update(s.encode('utf-8'))  # 将要产生md5的子串放进去

            if user.password_hash == md5.hexdigest():
                request.session['webuser'] = user.toDict()
                shopob = Shop.objects.get(id=request.POST['shop_id'])
                request.session['shopinfo'] = shopob.toDict()

                # 获取当前店铺中所有的菜品类别和菜品信息
                clists = Category.objects.filter(shop_id=shopob.id, status=1)
                categorylist = dict()  # 菜品类别（内含有菜品信息）
                productlist = dict()  # 菜品信息
                # 封装菜品信息到session
                for clist in clists:
                    c_dict = {'id': clist.id, 'name': clist.name, 'pids': []}
                    plists = Product.objects.filter(category_id=clist.id, status=1)
                    for plist in plists:
                        c_dict['pids'].append(plist.toDict())
                        productlist[plist.id] = plist.toDict()
                    categorylist[clist.id] = c_dict
                request.session['categorylist'] = categorylist
                request.session['productlist'] = productlist

                return redirect(reverse("web_index"))
            else:
                return redirect(reverse('web_login') + "?errinfo=5")
        else:
            return redirect(reverse('web_login') + "?errinfo=4")
    except Exception:
        return redirect(reverse('web_login') + "?errinfo=3")


def logout(request):
    """ 执行前台退出操作 """
    del request.session['webuser']
    return redirect(reverse('web_login'))


def verify(request):
    """生成验证码 """
    import random
    from PIL import Image, ImageDraw, ImageFont
    # 定义画面的背景色、宽、高
    bgcolor = (242, 164, 247)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str1 = '0123456789'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象
    font = ImageFont.truetype('static/arial.ttf', 21)
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, -3), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, -3), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, -3), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, -3), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    request.session['verifycode'] = rand_str
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端
    return HttpResponse(buf.getvalue(), 'image/png')
